package com.learn.demo.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * RabbitMQ死信配置
 *
 * @author banjiawei
 * @date 2021/12/12
 */
@Configuration
public class RabbitMQDeadLetterConfig {
    /**普通exchange名称*/
    public static final String GENERAL_EXCHANGE = "general.exchange";
    /**普通队列，设置过期时间*/
    public static final String GENERAL_QUEUE = "general.queue";
    /**普通队列的routing key*/
    public static final String GENERAL_KEY = "general.key";
    /**死信队列*/
    public static final String DEAD_LETTER_QUEUE = "dead.letter.queue";
    /**死信队列的routing key*/
    public static final String DEAD_LETTER_KEY = "dead.letter.key";

    @Bean
    public TopicExchange generalExchange(){
        return new TopicExchange(GENERAL_EXCHANGE, true, false);
    }

    @Bean
    public Queue generalQueue(){
        Map<String, Object> map = new HashMap<>();
        /*普通队列消息过期时间，20s*/
        map.put("x-message-ttl", TimeUnit.SECONDS.toMillis(20));
        map.put("x-dead-letter-exchange", GENERAL_EXCHANGE);
        /*消息转发到死信队列的routing key*/
        map.put("x-dead-letter-routing-key", DEAD_LETTER_KEY);
        return new Queue(GENERAL_QUEUE, true, false, false, map);
    }

    @Bean
    public Binding generalQueueBinding(){
        return BindingBuilder.bind(generalQueue()).to(generalExchange()).with(GENERAL_KEY);
    }

    @Bean
    public Queue deadLetterQueue(){
        return new Queue(DEAD_LETTER_QUEUE, true);
    }

    @Bean
    public Binding deadLetterQueueBinding(){
        return BindingBuilder.bind(deadLetterQueue()).to(generalExchange()).with(DEAD_LETTER_KEY);
    }
}
